package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.ClockingBaseBean;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.config.AppDataSource;
import com.android.infantschool.model.mvp.presenter.ClockBasePresenter;
import com.android.infantschool.model.mvp.presenter.ClockBasePresenterImpl;
import com.android.infantschool.model.mvp.view.ClockBaseView;
import com.android.infantschool.ui.adapter.ClockingBaseAdapter;
import com.android.infantschool.ui.dialog.DialogSearchBle;
import com.android.infantschool.ui.view.calendar.utils.DataUtils;
import com.android.infantschool.util.DateUtil;
import com.android.infantschool.util.LocationUtil;
import com.android.infantschool.util.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BabyThermometryActivity extends BaseActivity implements ClockingBaseAdapter.OnLister, ClockBaseView {

    @BindView(R.id.img_back)
    public ImageView imgBack;
    @BindView(R.id.title)
    public RelativeLayout rlTitle;
    @BindView(R.id.tv_title)
    public TextView tvTitle;
    @BindView(R.id.recyclerView)
    public RecyclerView recyclerView;

    public ClockingBaseAdapter adapter;
    @BindView(R.id.tv_thermometry)
    public TextView tvThermometry;
    @BindView(R.id.view_thermometry)
    public View viewThermometry;
    @BindView(R.id.tv_record)
    public TextView tvRecord;
    @BindView(R.id.view_record)
    public View viewRecord;

    private DialogSearchBle dialogSearchBle;

    private int TYPE_LAYOUT = 6;//保存当前请求的哪个界面的数据

    /**
     * 取得默认的蓝牙适配器
     */
    private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    /**
     * 连接到的蓝牙设备
     */
    private Map<String, String> mapDevice = new HashMap<>();

    public static Intent newIntent(Activity activity) {
        Intent intent = new Intent(activity, BabyThermometryActivity.class);
        return intent;
    }

    private ClockBasePresenter basePresenter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baby_temperature);
        ButterKnife.bind(this);
        initView();
        registerReceiver();
    }

    public void registerReceiver() {
        IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        discoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, discoveryFilter);
    }

    private void initView() {
        basePresenter = new ClockBasePresenterImpl(this);
        rlTitle.setPadding(0, this.height, 0, 0);
        tvTitle.setText("宝宝测温");
        adapter = new ClockingBaseAdapter(this, this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setAdapter(adapter);

        boolean isStart = mBtAdapter.startDiscovery();
        Log.e(TAG, " 开始搜索蓝牙状态:" + isStart);
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                Log.e(TAG, "初始化完成,当前扫描到的设备:" +
                        device.getName() + "," + device.getAddress());
                if (mapDevice.containsKey("BF4030")) {
                    if (mapDevice.get("BF4030").startsWith("0F:03")) {
                        dismissSerrchBle();
                        ToastUtil.showShortToast(BabyThermometryActivity.this, "搜索成功");
                        break;
                    }
                } else {
                    mapDevice.put(device.getName(), device.getAddress());
                }
            }
            Log.e(TAG, "map:" + mapDevice.toString());
        } else {
            Log.e(TAG, "初始化完成,没有搜索到设备");
        }
    }

    private void getBabyInfo(int type) {
        TYPE_LAYOUT = type;
        Map<String, String> map = new HashMap<>();
        map.put("token", AppConfig.getToken());
        map.put("day", DateUtil.getDate(DateUtil.ymd));
        map.put("type", String.valueOf(type));
        Log.e(TAG, "map:" + map.toString());
        basePresenter.getClockBase(map);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "action:" + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                if (!mapDevice.containsKey(device.getName())) {
                    if (device.getName() == null || device.getAddress() == null) {
                        return;
                    }
                    if (device.getName().equals("BF4030") && device.getAddress().startsWith("0F:04")) {
                        return;
                    }

                    if (mapDevice.containsKey("BF4030")) {
                        if (mapDevice.get("BF4030").startsWith("0F:03")) {
                            dismissSerrchBle();
                            ToastUtil.showShortToast(BabyThermometryActivity.this, "搜索成功");
                            return;
                        }
                    }

                    int a2dp = mBtAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
                    int headset = mBtAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
                    int health = mBtAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);
                    int flag = -1;
                    if (a2dp == BluetoothProfile.STATE_CONNECTED) {
                        flag = a2dp;
                    } else if (headset == BluetoothProfile.STATE_CONNECTED) {
                        flag = headset;
                    } else if (health == BluetoothProfile.STATE_CONNECTED) {
                        flag = health;
                    }
                    if (flag != -1) {
                        mBtAdapter.getProfileProxy(BabyThermometryActivity.this, new BluetoothProfile.ServiceListener() {
                            @Override
                            public void onServiceDisconnected(int profile) {
                                // TODO Auto-generated method stub
                            }

                            @Override
                            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                                // TODO Auto-generated method stub
                                List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
                                if (mDevices != null && mDevices.size() > 0) {
                                    for (BluetoothDevice device : mDevices) {
                                        Log.e(TAG, "device name: " + device.getName() + "," + device.getAddress());
                                    }
                                } else {
                                    Log.e(TAG, "mDevices is null");
                                }
                            }
                        }, flag);
                    } else {

                    }
                    mapDevice.put(device.getName(), device.getAddress());
                    Log.e(TAG, "搜索到的蓝牙设备:" + device.getName() + "," + device.getAddress());
                    if (device.getName().equals("BF4030") && device.getAddress().startsWith("0F:03")) {
                        dismissSerrchBle();
                        ToastUtil.showShortToast(BabyThermometryActivity.this, "搜索成功");
                    }
                }
                //}
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                Log.e(TAG, "未搜索到蓝牙设备");
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3 && resultCode == Activity.RESULT_OK) {
            Log.e(TAG, "蓝牙授权成功");
            showSearchBle();
            if (mBtAdapter.isDiscovering()) {
                boolean isCancel = mBtAdapter.cancelDiscovery();
                Log.e(TAG, " 取消搜索蓝牙状态:" + isCancel);
            }
            boolean isStart = mBtAdapter.startDiscovery();
            Log.e(TAG, " 开始搜索蓝牙状态:" + isStart);
        }
        if (requestCode == 4 && resultCode == Activity.RESULT_OK) {
            Log.e(TAG, "位置服务已打开");
            if (!mBtAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, 3);
                return;
            }
        }
    }

    private void showSearchBle() {
        if (dialogSearchBle != null) {
            dialogSearchBle.dismiss();
            dialogSearchBle = null;
        }
        dialogSearchBle = new DialogSearchBle(this);
        dialogSearchBle.show();
    }

    private void dismissSerrchBle() {
        if (dialogSearchBle != null) {
            dialogSearchBle.dismiss();
            dialogSearchBle = null;
        }
    }

    @OnClick({R.id.img_back, R.id.tv_thermometry, R.id.tv_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                this.finish();
                break;
            case R.id.tv_thermometry:
                showThermometry();
                break;
            case R.id.tv_record:
                showReCord();
                break;
        }
    }

    public void showThermometry() {
        tvThermometry.setTextColor(0xFF007C70);
        tvRecord.setTextColor(0xFF000000);
        viewRecord.setVisibility(View.GONE);
        viewThermometry.setVisibility(View.VISIBLE);
        this.showLoading();
        getBabyInfo(6);
    }

    public void showReCord() {
        tvRecord.setTextColor(0xFF007C70);
        tvThermometry.setTextColor(0xFF000000);
        viewThermometry.setVisibility(View.GONE);
        viewRecord.setVisibility(View.VISIBLE);
        this.showLoading();
        getBabyInfo(7);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (basePresenter != null) {
            basePresenter.onDestroy();
            basePresenter = null;
        }
        mapDevice.clear();
        if (mReceiver != null) {
            this.unregisterReceiver(mReceiver);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG,"onResume...");
        this.showLoading();
        getBabyInfo(TYPE_LAYOUT);
    }

    @Override
    public void errorClockBase(String error) {
        this.dismissLoading();
        adapter.clear();
        ToastUtil.showShortToast(this, "网络异常:" + error);
    }

    @Override
    public void successClockBase(BaseBean baseBean) {
        this.dismissLoading();
        ClockingBaseBean bean = (ClockingBaseBean) baseBean;
        if (bean.getCode() == 0) {
            adapter.setData(bean.getData(), TYPE_LAYOUT);
        } else {
            adapter.clear();
            ToastUtil.showShortToast(this, "获取失败:" + bean.getMsg());
        }
    }

    @Override
    public void lister(int position, int type) {
        switch (type) {
            case 6://去测温
                if (mBtAdapter == null) {
                    ToastUtil.showShortToast(this, "设备不支持蓝牙");
                    return;
                }

                if (!LocationUtil.isLocServiceEnable(this)) {
                    LocationUtil.showGPSContacts(this, 4);
                    return;
                }

                if (!mBtAdapter.isEnabled()) {
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, 3);
                    return;
                }
                if (mapDevice.containsKey("BF4030")) {
                    if (mBtAdapter.isDiscovering()) {
                        boolean isCancel = mBtAdapter.cancelDiscovery();
                        Log.e(TAG, " 取消搜索蓝牙状态:" + isCancel);
                    }
                    startActivity(ThermometryActivity.newIntent(this, "BF4030", mapDevice.get("BF4030"), adapter.list.get(position).getName(), String.valueOf(adapter.list.get(position).getId())));
                } else {
                    showSearchBle();
                    if (mBtAdapter.isDiscovering()) {
                        boolean isCancel = mBtAdapter.cancelDiscovery();
                        Log.e(TAG, " 取消搜索蓝牙状态:" + isCancel);
                    }
                    boolean isStart = mBtAdapter.startDiscovery();
                    Log.e(TAG, " 开始搜索蓝牙状态:" + isStart);
                }
                break;
            case 7://测温记录
                startActivity(TemperatureCodeActivity.newIntent(this, adapter.list.get(position).getName(), String.valueOf(adapter.list.get(position).getId())));
                break;
        }
    }
}